import Vue from 'vue'

import 'normalize.css/normalize.css' // A modern alternative to CSS resets

import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import locale from 'element-ui/lib/locale/lang/zh-CN' // lang i18n

import '@/styles/index.scss' // global css

import App from './App'
import router from './router'
import store from './store'
import request from '@/utils/request'

import '@/icons' // icon
import '@/permission' // permission control

import * as filters from './filters' // global filters

Vue.use(ElementUI, {
  locale
})

// 注册全局过滤器
Object.keys(filters).forEach(key => {
  Vue.filter(key, filters[key])
})

/**
 * 注册异步请求工具
 * @type {Object}
 */
Vue.prototype.$http = {
  ...request
}

/**
 * 注册其他工具
 * @type {Object}
 */
Vue.prototype.$error = function(messageOrResponse, callback = undefined) {
  let message = messageOrResponse
  if (typeof messageOrResponse !== 'string') {
    const response = messageOrResponse
    const errorMsg = []
    for (const key in response.errors) {
      if (response.errors.hasOwnProperty(key)) {
        const element = response.errors[key]
        errorMsg.push(element.join('<br>'))
      }
    }
    if (errorMsg.length > 0) {
      message = errorMsg.join('<br>')
    } else {
      message = response.message
    }
  }
  if (callback) {
    this.$alert(message, {
      title: '错误提示',
      type: 'error',
      callback
    })
  } else {
    this.$alert(message, {
      title: '错误提示',
      type: 'error'
    })
  }
  throw new Error()
}
Vue.prototype.$success = function(message) {
  this.$message({
    message,
    duration: 2000,
    type: 'success',
    showClose: true
  })
}
const $confirm = Vue.prototype.$confirm
Vue.prototype.$confirm = function(message, okCallback, cancelCallback) {
  $confirm(message, '系统提示', {
    type: 'warning'
  })
    .then(() => {
      okCallback && okCallback()
    })
    .catch(() => {
      cancelCallback && cancelCallback()
    })
}

/**
 * 注册异步下载工具
 * @type {Object}
 */
Vue.prototype.$download = function(responseData, filename) {
  if (responseData) {
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(new Blob([responseData]))
    link.setAttribute('download', filename)
    link.click()
  }
}

Vue.config.productionTip = false

new Vue({
  el: '#app',
  router,
  store,
  render: h => h(App)
})
